package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.MdmFacilityVersionAddDto;
import com.kaili.basic.pojo.dto.MdmFacilityVersionDto;
import com.kaili.basic.pojo.entity.MdmFacilityVersion;
import com.kaili.basic.pojo.vo.MdmFacilityVersionVO;
import com.kaili.basic.service.IFacilityVersionService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.fastdfs.UploadController;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.LoginDetailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc: 版本设置控制类
 * @author: PF12Z08Z
 * @Time: 2019/7/25 18:54
 * @Copyright: © 2018 杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅, 禁止外泄或用于其它商业目的
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "版本设置", description = "版本设置相关API")
@RestController
public class MdmFacilityVersionController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IFacilityVersionService facilityVersionService;

    /**
    *自动生成版本编码
    *@author:linjian
    *@Time:2019/7/25 18:58
    *@param
    *@return
    */
    @ApiOperation(value = "自动生成版本编码", notes = "自动生成版本编码")
    @PostMapping("/facility/versionCode")
    public String autoCreateCompanyCode(){
        //在跳转到版本设置页面的时候，首先查询是否存在可以使用的编码，若不存在，就自动生成返回给前端
        String code =  facilityVersionService.getUsableCode();
        if (null == code){
            Map<String,Object> timeMap = new HashMap<>();
            Date createdTime = new Date();
            Date optTime = new Date();
            timeMap.put("createdTime",createdTime);
            timeMap.put("optTime",optTime);
            facilityVersionService.createdVersionCode(timeMap);
            code = facilityVersionService.getUsableCode();
        }
        String zero = "0";
        if (code.length()<9){
            int index = 9 - code.length();
            for (int i = 0;i<index;i++){
                code = zero+code;
            }
        }
        return code;
    }

    /**
    *按条件查询版本
    *@author:linjian
    *@Time:2019/7/25 19:43
    *@param dto
    *@return
    */
    @ApiOperation(value = "分页查询版本信息", notes = "分页查询版本信息")
    @GetMapping("/facility")
    public Page<MdmFacilityVersionVO> queryFacilityVersionByConditions(@ModelAttribute MdmFacilityVersionDto dto){
        Page<MdmFacilityVersionVO> page = facilityVersionService.queryFacilityVersionByConditions(new Page<MdmFacilityVersionVO>(dto.getPage(), dto.getPageSize()),dto);
        return page;
    }


    /**
     *查询所有版本
     *@author:linjian
     *@Time:2019/7/25 19:43
     *@param null
     *@return
     */
    @ApiOperation(value = "查询所有版本信息", notes = "查询所有版本信息")
    @GetMapping("/facility/queryAll")
    public List<MdmFacilityVersionVO> queryAllFacilityVersion(){
        List<MdmFacilityVersionVO> list = facilityVersionService.queryAllFacilityVersion();
        return list;
    }

    /**
    *文件上传
    *@author:linjian
    *@Time:2019/7/29 10:43
    *@param file,dto
    *@return
    */
    @ApiOperation(value = "版本上传")
    @PostMapping("/facility/upload")
    public RestStatus addDocument(@RequestParam("file") MultipartFile file , MdmFacilityVersionAddDto dto){
        MdmFacilityVersion entity = getFormData(dto,file);
        entity.setRdStatus("1");
        MdmFacilityVersion facility = facilityVersionService.queryVersionByCode(dto.getVersionCode());
        if (null != facility){
            return CommonStatus.ADD_DEFEAT;
        }else{
            //变更编码状态为正在使用
            facilityVersionService.updateVersionCodeStatusUsing(entity.getVersionCode());
            entity.setCreatedBy(LoginDetailUtils.getCurrentEmployeeId());
            entity.setCreatedTime(new Date());
            int result = facilityVersionService.addDocument(entity);
            if (result == 1){
                //新增成功后变更编码使用状态为已使用
                facilityVersionService.updateVersionCodeStatusUsed(entity.getVersionCode());
                return CommonStatus.ADD_OK;
            }else{
                //新增失败,变更编码使用状态为未使用
                facilityVersionService.updateVersionCodeStatusUnuse(entity.getVersionCode());
                return CommonStatus.ADD_DEFEAT;
            }
        }

    }

    private MdmFacilityVersion getFormData(MdmFacilityVersionAddDto dto, MultipartFile file) {
        MdmFacilityVersion entity = new MdmFacilityVersion();
        BeanUtils.copyProperties(dto,entity);
        try {
            if (file != null && file.getSize() != 0) {
                String path = UploadController.saveFile(file);
                entity.setFileUrl(path);
            }
        } catch (IOException e) {
            logger.debug("文件获取异常:"+e);
        }
        return entity;
    }

    public String replaceCode(String versionCode){
        Long code = Long.parseLong(versionCode);
        return code.toString();
    }
}
